package com.netty.unit1nio.c2;

import com.netty.unit1nio.c1.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Slf4j
public class server {
    public static void main(String[] args) throws IOException {
//创建Selector管理多个channel
        Selector selector = Selector.open();

        //
        ByteBuffer  buffer=ByteBuffer.allocate(16);

        //创建服务器
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);//非阻塞模式，接收连接的时候非阻塞

        //建立Selector和channel的连接(注册) 注册需要在非阻塞的状态下注册
        SelectionKey sscKey = ssc.register(selector, 0, null);
sscKey.interestOps(SelectionKey.OP_ACCEPT);

        //绑定端口
        ssc.bind(new InetSocketAddress(8080));
        //建立连接
        //SocketChannel是对 TCP 网络连接（Socket）的封装，用于非阻塞网络通信
        List<SocketChannel> socketChannels=new ArrayList<>();
        while(true){
       selector.select();//阻塞，等待channel发生事件   有事件未处理时不会阻塞
            //获取发生了事件的channel的key的集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while(iterator.hasNext()){
                SelectionKey key = iterator.next();
              //  key.cancel();//取消处理事件
                log.debug("key:{}",key);
                ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                channel.accept();
                log.debug("connected...");
            }
        }
    }
}